﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Media.Media3D;

namespace Yang
{
    public  class ScreenShot : IDisposable
    {
        private IntPtr window;
        private IntPtr dc;
        private IntPtr memDC;
        private IntPtr memImg;
        public WindowAPI.RECT windowRect;

        public ScreenShot()
        {
            window = WindowAPI.FindWindow("Chrome_WidgetWin_0", "羊了个羊");
            dc = WindowAPI.GetWindowDC(IntPtr.Zero);
            windowRect = new WindowAPI.RECT();
            WindowAPI.GetWindowRect(window, ref windowRect);
            memDC = WindowAPI.CreateCompatibleDC(dc);
            int width = windowRect.right - windowRect.left;
            int height = windowRect.bottom - windowRect.top;
            memImg = WindowAPI.CreateCompatibleBitmap(dc, width, height);
        }

        public IntPtr GetImage(string path)
        {
            WindowAPI.GetWindowRect(window, ref windowRect);
            int width = windowRect.right - windowRect.left;
            int height = windowRect.bottom - windowRect.top;
            WindowAPI.SelectObject(memDC, memImg);

            var result = WindowAPI.BitBlt(memDC, 0, 0, width, height, dc, windowRect.left, windowRect.top, 0xCC0020);
            var rv = System.Drawing.Image.FromHbitmap(memImg);
            rv.Save(path);
            return memImg;
        }

        public void Dispose()
        {
            WindowAPI.DeleteObject(memImg);
            WindowAPI.DeleteDC(memDC);
            WindowAPI.DeleteDC(dc);
            WindowAPI.DeleteObject(window);
        }
    }
}
